using System;
using GHIElectronics.NETMF.Hardware;

namespace InternetThermostat.Models
{
    public static class Schedule
    {
        public static int TargetTemperature { get; set; }

        public static Dictionary WeeklySchedule = new Dictionary();

        public static Dictionary Override = new Dictionary();

        public static ValuePair GetNext(DayTime time, Dictionary schedule)
        {
            var curMins = MinutesFromNewWeek(time);

            int closest = int.MaxValue;
            int mostNegative = int.MaxValue;
            ValuePair closestTime = null;
            ValuePair closestNextWeekTime = null;

            foreach (var pair in schedule)
            {
                var pairMins = MinutesFromNewWeek(((ValuePair)pair).Key);
                if (pairMins - curMins > 0 && pairMins - curMins < closest)
                {
                    closest = pairMins - curMins;
                    closestTime = (ValuePair)pair;
                }
                else if (pairMins - curMins < 0 && pairMins - curMins < mostNegative)
                {
                    mostNegative = pairMins - curMins;
                    closestNextWeekTime = (ValuePair)pair;
                }
            }

            if (closest != int.MaxValue)
                return closestTime;
            else if (mostNegative != int.MaxValue)
                return closestNextWeekTime;
            else
                throw new ArgumentOutOfRangeException("Could not find next scheduled item");
        
        }

        public static ValuePair GetNextOverrideTemperature(DateTime now = default(DateTime))
        {
            if (now == default(DateTime))
                now = RealTimeClock.GetTime();

            var curDayTime = new DayTime { Day = now.DayOfWeek, Hour = (byte)now.Hour, Minute = (byte)now.Minute };
            
            return GetNext(curDayTime, Schedule.Override);          
            
        }

        public static ValuePair GetNextScheduledTemperature(DateTime now = default(DateTime))
        {
            if (now == default(DateTime))
                now = RealTimeClock.GetTime();

            var curDayTime = new DayTime { Day = now.DayOfWeek, Hour = (byte)now.Hour, Minute = (byte)now.Minute };

            return GetNext(curDayTime, Schedule.WeeklySchedule);  


        }

        private static int MinutesFromNewWeek(DayTime dayTime)
        {
            return (int)dayTime.Day * 24 * 60 + dayTime.Hour * 60 + dayTime.Minute;
        }


    }
}
